<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>

        <el-radio-group v-model="treeProps" style="margin-right: 50px;">
          <el-radio-button label="资产">资产</el-radio-button>
          <el-radio-button label="负债">负债</el-radio-button>
          <el-radio-button label="权益">权益</el-radio-button>
          <el-radio-button label="成本">成本</el-radio-button>
          <el-radio-button label="损益">损益</el-radio-button>
        </el-radio-group>

        {{treeProps}}

        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:subject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="subjectList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="科目编码" align="center" prop="code" />
      <el-table-column label="科目名称" align="center" prop="name" />
      <el-table-column label="助记码" align="center" prop="mnemonicCode" />
      <el-table-column label="余额方向" align="center" prop="balanceDirection" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:subject:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:subject:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:subject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改科目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="subjectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科目编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入科目编码" />
        </el-form-item>
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="助记码" prop="mnemonicCode">
          <el-input v-model="form.mnemonicCode" placeholder="请输入助记码" />
        </el-form-item>
        <el-form-item label="上级科目" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="subjectOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择上级科目"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="余额方向" prop="balance">
          <el-input v-model="form.balanceDirection" placeholder="请输入余额方向" />
        </el-form-item>
        <el-form-item label="状态" prop="balance">
          <el-input v-model="form.status" placeholder="状态" />
        </el-form-item>
        <el-form-item label="数量核算" prop="unit">
          <el-input v-model="form.currencyAccounting" placeholder="数量核算" />
        </el-form-item>
        <el-form-item label="辅助核算" prop="auxiliaryAccounting">
          <el-input v-model="form.auxiliaryAccounting" placeholder="辅助核算" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Subject">
import { listSubject, getSubject, delSubject, addSubject, updateSubject } from "@/api/system/subject";
import {ElMessage} from "element-plus";

const { proxy } = getCurrentInstance();

const subjectList = ref([]);
const subjectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const treeProps  = ref('资产')

watch(treeProps,(New, Old)=>{
  getList()
})


const data = reactive({
  form: {},
  queryParams: {
    type: null,
  },
  rules: {
    type: [
      { required: true, message: "科目类型不能为空", trigger: "change" }
    ],
    code: [
      { required: true, message: "科目编码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "科目名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    level: [
      { required: true, message: "所在级别不能为空", trigger: "blur" }
    ],
    systemDefault: [
      { required: true, message: "是否为系统默认不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询科目管理列表 */
function getList() {
  let setsId = sessionStorage.getItem("setsId");
  if(setsId == null){
    ElMessage({
      message: '请先选择账套信息',
      type: 'warning',
    })
    loading.value = false;
    return;
  }
  loading.value = true;
  queryParams.value['accountSetsId'] =  setsId
  queryParams.value['type'] =  treeProps.value

  listSubject(queryParams.value).then(response => {
    subjectList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}

/** 查询科目管理下拉树结构 */
function getTreeselect() {
  let setsId = sessionStorage.getItem("setsId");

  listSubject({accountSetsId:setsId, type:treeProps.value}).then(response => {
    subjectOptions.value = [];
    const data = { id: 0, name: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    subjectOptions.value.push(data);
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    code: null,
    name: null,
    mnemonicCode: null,
    balanceDirection: null,
    status: null,
    parentId: null,
    level: null,
    systemDefault: null,
    accountSetsId: null,
    balance: null,
    unit: null,
    auxiliaryAccounting: null,
    currencyAccounting: null,
    parentCode: null
  };
  proxy.resetForm("subjectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加科目管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.id;
  }
  getSubject(row.id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科目管理";
  });
}

/** 提交按钮 */
function submitForm() {
  let setsId = sessionStorage.getItem("setsId");
  form.value.accountSetsId =  setsId
  form.value.type = treeProps.value

  proxy.$refs["subjectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSubject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSubject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除科目管理编号为"' + row.id + '"的数据项？').then(function() {
    return delSubject(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>
